#include "string.h"
#include "global.h"
#include "debug.h"

void memset(void* dst, uint8_t value, uint32_t size){
    uint8_t* _dst = dst;
    ASSERT(_dst != NULL);
    while(size-- > 0){
        *_dst++ = value;
    }
}

void memcpy(void* dst, void* src, uint32_t size){
    uint8_t* _dst = dst;
    const uint8_t* _src = src;

    ASSERT(_dst != NULL && _src != NULL);
    while(size-- > 0){
        *_dst++ = *_src++;
    }
}

int memcmp(void* dst, void* src, uint32_t size){
    const uint8_t* _dst = dst;
    const uint8_t* _src = src;

    ASSERT(_dst != NULL && _src != NULL);

    while(size-- > 0){
        if(*_dst != *_src){
            return *_dst > *_src ? 1 : -1;   
        }
        _dst ++, _src++;
    }

    return 0;
}

char* strcpy(char* dst, const char* src){
    ASSERT(dst != NULL && src != NULL);
    char* _dst_beta = dst;
    while((*dst++ = *src++));
    
    return _dst_beta;
}

uint32_t strlen(const char* str){
    ASSERT(str != NULL);
    const char* _str = str;
    while(*_str++);
    return (_str - str - 1);
}

int8_t strcmp(const char *a, const char *b){
    ASSERT(a != NULL && b != NULL);
    while(*a == *b && *a != '\0'){
        a++;
        b++;
    }
    /* 若a小于b返回-1 若a=b返回0 a>b返回1 */
    return *a < *b ? -1 : *a > *b;
}

char* strchr(const char* string, const uint8_t ch){
    ASSERT(string != NULL);
    char* _string = (char*)string;
    while(*_string != '\0'){
        if(*_string == ch)
            return _string;
        _string++;
    }
    return NULL;
}

char* strrchr(const char* string, const uint8_t ch){
    ASSERT(string != NULL);
    char* _string = (char*)string;
    char* _last_string = NULL;
    while(*_string != '\0'){
        if(*_string == ch)
            _last_string = _string;
        _string++;
    }
    return _last_string;
}

char* strcat(char* dst_, const char* src_){
    ASSERT(dst_ != NULL && src_ != NULL);
    char* _dst_beta = dst_;
    while(*dst_++);
    dst_ --;
    while((*dst_++ = *src_++));

    return _dst_beta;
}